package com.wyj.controller;

import com.wyj.event.EventProducer;
import com.wyj.pojo.Comment;
import com.wyj.pojo.DiscussPost;
import com.wyj.pojo.event;
import com.wyj.service.imp.CommentServiceImp;
import com.wyj.service.imp.DiscussPostServiceImp;
import com.wyj.util.CommunityConstant;
import com.wyj.util.HostHolder;
import com.wyj.util.RedisKeyUtil;
import com.wyj.util.RedisUtil;
import lombok.extern.log4j.Log4j2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @author 王永杰
 * @Description 描述该类的做什么用
 * @since 2022/7/18
 */
@Controller
@Log4j2
public class CommentController implements CommunityConstant {

    @Autowired
    CommentServiceImp commentServiceImp;

    @Autowired
    HostHolder hostHolder;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    DiscussPostServiceImp discussPostServiceImp;

    @Autowired
    EventProducer eventProducer;

    //   private static final Logger logger = LoggerFactory.getLogger(CommentController.class);

    @RequestMapping(value = "/add/{id}", method = RequestMethod.POST)
    public String addComment(@PathVariable("id") int id, Comment comment) {
        comment.setUserId(hostHolder.getUser().getId());
        comment.setCreateTime(new Date());
        comment.setStatus(0);

        log.info("新增的评论:" + comment);

        int i = commentServiceImp.addComment(comment);
        if (i <= 0) {
            log.info("增加评论失败");
        }

        //触发评论事件
        event event = new event();

        event.setTopic(TOPIC_COMMENT);
        event.setUserId(hostHolder.getUser().getId());
        event.setEntityType(comment.getEntityType());//评论实体的类型
        event.setEntityId(comment.getEntityId());//评论实体的id
        event.setData("postId", id);

        eventProducer.fireEvent(event);

        //对帖子的评论
        if (comment.getEntityType() == ENTITY_TYPE_POST) {
            DiscussPost discussPost = discussPostServiceImp.getDiscussPost(id);
            event.setEntityUserId(discussPost.getUserId());
        } else if (comment.getEntityType() == ENTITY_TYPE_COMMENT) { //对评论的回复
            Comment target = commentServiceImp.getCommentById(comment.getEntityId());
            event.setEntityUserId(target.getUserId());
        }
        //将事件发布到主题当中
        eventProducer.fireEvent(event);


        //计算分数
        String postScore = RedisKeyUtil.getPostScore();
        redisUtil.sSet(postScore, id);

//        log.info("==================="+ redisUtil.setGetPop(postScore));


        return "redirect:/getDiscussPost/" + id;
    }
}
